package net.monkeybros.sbus;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import net.monkeybros.sbus.model.InfoVehiculo;
import uk.me.jstott.jcoord.LatLng;
import uk.me.jstott.jcoord.UTMRef;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class BusMapActivity extends MapActivity {
	private static final String URL = "http://www.ayto-santander.es:9001";
	private Dinamica dinamica = new Dinamica();
	private Vector<InfoVehiculo> vInfoVehiculo = new Vector<InfoVehiculo>(); MapView mapView;
	private String lineSelected = "1";

	@Override
	protected void onCreate(Bundle icicle) {

		super.onCreate(icicle);
		setContentView(R.layout.bus_lines_map);
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		dinamica.globalBaseUrl = URL;
		updateBusesPosition(lineSelected);
		handler.postDelayed(runnable, 5000);

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public void updateBusesPosition(String line) {
		mapView.getOverlays().clear();
		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.google_map_marker_red);
		LineBusesItemizedOverlay itemizedoverlay = new LineBusesItemizedOverlay(drawable, this);

		if (!vInfoVehiculo.isEmpty()) {
			vInfoVehiculo.clear();
		}
		
		try {
			vInfoVehiculo = dinamica.GetVehiculos(line);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (vInfoVehiculo != null) {
			Iterator it = vInfoVehiculo.iterator();
			InfoVehiculo ve;
			while (it.hasNext()) {
				ve = (InfoVehiculo) it.next();

				UTMRef utm = new UTMRef(ve.getxcoord(), ve.getycoord(), 't', 30);
				LatLng ll = utm.toLatLng();
				Log.i("Map Buses", " linea: " + ve.getlinea() + " sublinea: " + ve.getsublinea()
						+ " xcoord: " + ((int) (ll.getLat() * 1000000)) + " ycoord: "
						+ ((int) (ll.getLng() * 1000000)));
				GeoPoint point = new GeoPoint((int) (ll.getLat() * 1000000), (int) (ll.getLng() * 1000000));
				OverlayItem overlayitem = new OverlayItem(point, "Linea " + ve.getlinea(), "Sublinea: "
						+ ve.getserv_bus() + " __" + point.toString());
				itemizedoverlay.addOverlay(overlayitem);
			}
		}

		mapOverlays.add(itemizedoverlay);
		

	}

	private Handler handler = new Handler();

	private Runnable runnable = new Runnable() {

		public void run() {

			updateBusesPosition(lineSelected);

			/*
			 * Now register it for running next time
			 */

			handler.postDelayed(this, 5000);
		}

	};
	
}
